import { Component, OnInit } from '@angular/core'
import { Location } from '@angular/common'
import { Router, ActivatedRoute, Params } from '@angular/router'
import { CommonUtil } from 'src/app/common/utils/common.util'
import { LoginService } from 'src/app/common/services/login.service'
import { CoolLocalStorage } from 'src/app/common/coolStorage/cool-local-storage'

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {
  // 手机号码
  phone = ''

  // 验证码长度
  maxlength: number = 6
  // 验证码数组值
  captchaArray = []
  // 验证码字符串值
  captcha = ''
  // 登录中
  loging = false

  constructor(
    private location: Location,
    private router: Router,
    private activatedRoute: ActivatedRoute,
    private utils: CommonUtil,
    private loginService: LoginService,
    private storage: CoolLocalStorage
  ) {
    activatedRoute.params.subscribe((params: Params) => {
      this.phone = params.phone
    })
  }

  ngOnInit() {
    for (let i = 0; i < this.maxlength; i++) {
      this.captchaArray.push('')
    }
  }

  // 返回上一页
  onClickLeft() {
    this.location.back()
  }
  // 验证码匹配校验
  checkCaptcha() {
    this.loging = true
    let reqdata = { target: this.phone, captcha: this.captcha }
    this.loginService.checkCaptcha(reqdata, res => {
      if (res.Success && res.Result) {
        this.loginRequest()
      } else {
        this.loging = false
        this.utils.info('验证码错误，请重新输入')
      }
    })
  }
  // 登录
  loginRequest() {
    let reqdata = {
      website: 'CowX.House1.Consumer.WXMP',
      token: this.phone,
      role: '普通会员',
      nick: this.utils.encryPhone(this.phone),
      account: this.phone,
      introducer: null,
      captcha: this.captcha
    }
    this.loginService.login(
      reqdata,
      res => {
        let msg = '登录失败，请重试'
        this.loging = false
        if (res.Success && res.Result) {
          this.utils.success('登录成功')
          this.storage.setItem('token', res.Result)
          this.router.navigate(['/workspace/mine/index'])
        } else {
          if (res.Message && res.Message.indexOf('|') > -1) {
            msg = res.Message.split('|')[0]
          }
          this.utils.info(msg)
        }
      },
      () => {
        this.loging = false
        this.utils.fail('网络异常，请重试')
      }
    )
  }
}
